<?php

namespace Beerus\Modules\Designer\Actions;

use Beerus\Modules\Designer\Controllers\KaDesignerController;
use Doraemon\model\DesignerAmountRecord;
use Doraemon\service\KaManage\Combo;
use Doraemon\tools\Log;
use Illuminate\Http\Request;
use Encore\Admin\Actions\RowAction;
use Doraemon\model\KaDesigner;
use App\Admin\Controllers\FileController;

class SetEffect extends RowAction
{
    public $name = '设为生效';

    public function handle($id)
    {
        //设为生效操作
        //获取该合同的累计收款金额
        $ka_info = KaDesigner::getById($id);
        $contract_number = $ka_info['contract_number'];
        $contract_amount = $ka_info['contract_amount'];
        //根据合同编号获取累计金额
        $condition['contract_number'] = $contract_number;
        $record_info = DesignerAmountRecord::getAllByCondition($condition);
        $all_amount = 0;
        if ($record_info){
            foreach ($record_info as $value){
                $all_amount = $all_amount + $value['amount'];
            }
        }
        if ($all_amount == 0){
            return $this->response()->error('无收款记录，不能设置为生效');
        }elseif (floatval($all_amount) == floatval($contract_amount)){
            //直接设置为生效
            $update_data['data_status'] = KaDesigner::STATUS_EFFECT;
            $ka_result = KaDesigner::updateById($id,$update_data);
            if ($ka_result){
                // 初始化设计师KA广告套餐信息
                if (!Combo::initDesignerComboDetail($id)) {
                    Log::info("设计师KA广告套餐信息初始化失败，订单ID：{$id}");
                }
                //增加子账号权益
                KaDesignerController::CreatEquity($id);
                return $this->response()->success('设为生效成功(*^__^*)')->refresh();
            }else{
                return $this->response()->error('设为生效失败,请稍后重试o(TωT)o');
            }
        }
    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }

        return $key;
    }
}
